#include "IOUtil.h"
#include <osgEarth/HTTPClient>
#include <fstream>

using namespace osgEarth;

IOUtil::IOUtil()
{
}


IOUtil::~IOUtil()
{
}

bool IOUtil::loadFile(std::string url, size_t& size, char** p)
{
	std::ifstream fin(url.c_str(), std::ifstream::binary);
	if (fin){
		fin.seekg(0, fin.end);
		size = fin.tellg();
		fin.seekg(0, fin.beg);
		char* buffer = 0;
		buffer = (char*)malloc(size);
		fin.read(buffer, size);
		fin.close();
		*p = buffer;
		return true;
	}
	return false;
}

bool IOUtil::getHttp(std::string url, size_t& size, char** p)
{
	for (int i = 0; i < 3; i++){
		HTTPClient http;
		//std::string url = location;
		HTTPResponse response = http.get(url);
		if (response.isOK())
		{
			//std::istream& st = response.getPartStream(0);
			std::string str = response.getPartAsString(0);
			//qDebug() << QString::fromStdString(str);
			size = str.length();
			char* buffer =0;
			buffer = (char*)malloc(size);
			memcpy(buffer, str.c_str(), size);
			*p = buffer;
			return true;
		}
	}
	return false;
}

bool IOUtil::get(std::string url, size_t& size, char** buffer)
{
	if (!(url.find("http") == std::string::npos)){
		return getHttp(url, size, buffer);
	}
	else{
		return loadFile(url, size, buffer);
	}
}